const Base = require('./base.js');
module.exports = class extends Base {
	orderStatus(str) {
		let code = 0;
		switch(str) {
			case '订单付款':
				code = 12;
				break;
			case '订单结算':
				code = 3;
				break;
			case '订单失效':
				code = 13;
				break;
			default:
				code = 13
				break;
		}
		return code;
	}

	orderType(str) {
		let code = '';
		switch(str) {
			case 1:
				code = '淘宝';
				break;
			case 2:
				code = '天猫';
				break;
			case 3:
				code = '聚划算';
				break;
			default:
				code = str
				break;
		}
		return code;
	}

	/*****
	 * 更新订单
	 *****/
	async updateOrderByExcel(order) {

		for(const v of order) {

			let query = {
				order_sn: v.order_sn,
				goods_id: v.goods_id,
				create_time: v.create_time,
				is_updated: 0
			}
			let map = {
				'create_time': v.create_time,
				'goods_name': v.goods_name,
				'goods_id': v.goods_id,
				'wangwang': v.wangwang,
				'shop': v.shop,
				'goods_number': v.goods_number,
				'goods_price': v.goods_price,
				'order_status': this.orderStatus(v.order_status),
				'order_type': v.order_type,
				'income_ratio': parseFloat(v.income_ratio) / 100,
				'divided_ratio': parseFloat(v.divided_ratio) / 100,
				'order_amount': v.order_amount,
				'effect_prediction': v.effect_prediction,
				'balance_amount': v.balance_amount,
				'estimated_revenue': v.estimated_revenue,
				'balance_time': v.balance_time || null,
				'commission_ratio': parseFloat(v.commission_ratio) / 100,
				'commission_amount': v.commission_amount,
				'order_sn': v.order_sn,
				'adzone_id': v.adzone_id,
				'site_id': v.site_id,
				'is_updated': 1,
			};

			let orderid = await this.transaction(async() => {
				let order = await this.where(query).find();
				let orderid = order.id;
				if(think.isEmpty(order)) {

					orderid = await this.add(map);

				} else {
					await this.setOne(order.id, map);
					if(order.user_id) {

						if(order.order_status != '3' && map.order_status == '3') {

							//订单结算
							await this.orderBalance(order);

						}

						if(order.order_status == '3' && map.order_status == '13') {

							//订单维权
							await this.ordeRefund(order);

						}
						if(order.order_status == '12' && map.order_status == '13') {

							//订单未结算维权
							await this.orderCancel(order);

						}

					}

				}
				return orderid;

			});

			let newOrder = await this.findOne(orderid);
			if(think.isEmpty(newOrder.user_id)) {
				await this.autoBindOrder(newOrder);
			}

		}

	}

	async updateOrderByJson(order) {

		for(const v of order) {
			console.log(v);
			let query = {
				order_sn: v.taobaoTradeParentId,
				goods_id: v.auctionId,
				create_time: v.create_time,
				is_updated: 0
			}
			let map = {
				'create_time': v.createTime,
				'goods_name': v.auctionTitle,
				'goods_id': v.auctionId,
				'wangwang': v.exNickName,
				'shop': v.exShopTitle,
				'goods_number': v.auctionNum,
				'goods_price': v.payPrice,
				'order_status': v.payStatus,
				'order_type': this.orderType(v.tkBizTag),
				'income_ratio': parseFloat(v.discountAndSubsidyToString) / 100,
				'divided_ratio': parseFloat(v.shareRate) / 100,
				'order_amount': v.totalAlipayFeeString,
				'effect_prediction': v.feeString,
				'balance_amount': v.realPayFeeString,
				'estimated_revenue': v.tkPubShareFeeString,
				'balance_time': v.earningTime || null,
				'commission_ratio': parseFloat(v.finalDiscountToString) / 100,
				'commission_amount': v.tkPubShareFeeString,
				'order_sn': v.taobaoTradeParentId,
				'is_updated': 1,
			};

			let orderid = await this.transaction(async() => {
				let order = await this.where(query).find();
				let orderid = order.id;
				if(think.isEmpty(order)) {

					orderid = await this.add(map);

				} else {
					await this.setOne(order.id, map);
					if(order.user_id) {

						if(order.order_status != '3' && map.order_status == '3') {

							//订单结算
							await this.orderBalance(order);

						}

						if(order.order_status == '3' && map.order_status == '13') {

							//订单结算后维权
							await this.ordeRefund(order);

						}
						if(order.order_status == '12' && map.order_status == '13') {

							//订单未结算维权
							await this.orderCancel(order);

						}

					}

				}
				return orderid;

			});

			let newOrder = await this.findOne(orderid);
			if(think.isEmpty(newOrder.user_id)) {
				await this.autoBindOrder(newOrder);
			}

		}

	}

	/*****
	 * 更新订单
	 *****/
	async updateOrder(order) {

		for(const v of order) {

			let query = {
				order_child_sn: v.trade_id
			}
			let map = {
				'order_sn': v.trade_parent_id, //主订单号
				'order_child_sn': v.trade_id, //子订单号
				'goods_name': v.item_title, //商品名称				
				'create_time': v.create_time, //创建时间
				'goods_id': v.num_iid, //商品ID
				'goods_number': v.item_num, //购买数量
				'order_status': v.tk_status, //订单状态				
				'wangwang': v.seller_nick,
				'shop': v.seller_shop_title,
				'goods_price': v.price, //商品原价				
				'income_ratio': v.income_rate, //收入比率				
				'divided_ratio': v.commission_rate, //分成比率				
				'order_amount': v.alipay_total_price, //付款金额
				'balance_time': v.earning_time, //结算时间				
				'effect_prediction': v.pub_share_pre_fee, //效果预估				
				'order_type': v.order_type,
				'balance_amount': v.pay_price, //结算金额				
				'estimated_revenue': v.commission, //预估收入				
				'commission_ratio': v.total_commission_rate, //佣金比率
				'commission_amount': v.total_commission_fee, //佣金金额
				'site_id': v.site_id,
				'adzone_id': v.adzone_id
			};

			let orderid = await this.transaction(async() => {
				let order = await this.where(query).find();
				let orderid = order.id;
				if(think.isEmpty(order)) {

					orderid = await this.add(map);

				} else {
					await this.setOne(order.id, map);
					if(order.user_id) {

						if(order.order_status != '3' && map.order_status == '3') {

							//订单结算
							await this.orderBalance(order);

						}

						if(order.order_status == '3' && map.order_status == '13') {

							//订单维权
							await this.ordeRefund(order);

						}
						if(order.order_status == '12' && map.order_status == '13') {

							//订单未结算维权
							await this.orderCancel(order);

						}

					}

				}
				return orderid;

			});

			let newOrder = await this.findOne(orderid);
			if(think.isEmpty(newOrder.user_id)) {
				await this.autoBindOrder(newOrder);
			}

		}

	}

	async autoBindOrder(order) {

		//		根据订单号后6位特征码找用户，如果没有找到特征码,就根据订单创建前10分钟内最近的公众号转化记录作为绑单用户依据;
		//		如果找到特征码,根据特征码绑单，根据商品编号找24小时内转化记录，两者刚好对应上作为绑单用户，两者不能对应上，不进行自动绑单。

		let feature = await think.model("taoke/feature").where({
			code: order.order_sn.slice(-6)
		}).find();
		let time = (new Date(order.create_time)).getTime();
		if(think.isEmpty(feature)) {

			let transfer = await think.model("taoke/transfer").where({
				goods_id: order.goods_id,
				source: 1,
				create_time: {
					'>': (time - 600 * 1000),
					'<': time
				}
			}).find();
			if(!think.isEmpty(transfer)) {
				let asset = await think.model("system/asset").where({
					user_id: transfer.user_id
				}).find();
				console.log(asset);
				if(!think.isEmpty(asset)) {
					await this.bindOrder(order, asset);
				}

			}

		} else {

			//			let transfer = await think.model("taoke/transfer").where({
			//				goods_id: order.goods_id,
			//				user_id: feature.user_id,
			//				create_time: {
			//					'>': (time - 48 * 3600 * 1000),
			//					'<': time
			//				}
			//			}).find();
			//
			//			if(!think.isEmpty(transfer)) {
			//				let asset = await think.model("system/asset").where({
			//					user_id: feature.user_id
			//				}).find();
			//				if(!think.isEmpty(asset)) {
			//					await this.bindOrder(order, asset);
			//				}
			//
			//			}

			let asset = await think.model("system/asset").where({
				user_id: feature.user_id
			}).find();
			if(!think.isEmpty(asset)) {
				await this.bindOrder(order, asset);
			}

		}

	}
	/*****
	 * 已绑订单结算
	 *****/
	async orderBalance(order) {

		await think.model("system/asset").db(this.db()).where({
			user_id: order.user_id
		}).increment('amount', order.buyer_commission);
		const balance = await think.model("system/asset").db(this.db()).where({
			user_id: order.user_id
		}).getField('amount', true);

		await think.model("system/money").db(this.db()).add({
			type: 6,
			create_time: new Date().valueOf(),
			amount: order.buyer_commission,
			balance: balance,
			status: 1,
			change: 1,
			user_id: order.user_id,
			note: `网购分红,订单编号【${order.order_sn}】`

		});
		await think.model("system/message").db(this.db()).add({
			type: 6,
			create_time: new Date().valueOf(),
			user_id: order.user_id,
			content: `订单【${order.order_sn}】完成购物,奖励您:${order.buyer_commission}元,您剩余${balance}元`

		});

		if(!think.isEmpty(order.agency_id)) {

			let agency = await think.model("system/agency").db(this.db()).findOne(order.agency_id);

			await think.model("system/asset").db(this.db()).where({
				user_id: agency.user_id
			}).increment('amount', order.recommend_commission);
			const balance = await think.model("system/asset").db(this.db()).where({
				user_id: agency.user_id
			}).getField('amount', true);

			await think.model("system/money").db(this.db()).add({
				type: 6,
				create_time: new Date().valueOf(),
				amount: order.recommend_commission,
				balance: balance,
				status: 1,
				change: 1,
				user_id: agency.user_id,
				note: `团队成员网购分红,订单编号【${order.order_sn}】`

			});
			await think.model("system/message").db(this.db()).add({
				type: 6,
				create_time: new Date().valueOf(),
				user_id: agency.user_id,
				content: `团队成员订单完成购物,奖励您:${order.recommend_commission}元,您剩余${balance}元`

			});

		}

	}

	/*****
	 * 已绑已结算订单退款
	 *****/

	async orderRefund(order) {
		await think.model("system/asset").db(this.db()).where({
			user_id: order.user_id
		}).decrement('amount', order.buyer_commission);
		await think.model("system/asset").db(this.db()).where({
			user_id: order.user_id
		}).decrement('rebate', order.buyer_commission);
		const balance = await think.model("system/asset").db(this.db()).where({
			user_id: order.user_id
		}).getField('amount', true);

		await think.model("system/money").db(this.db()).add({
			type: 6,
			create_time: new Date().valueOf(),
			amount: order.buyer_commission,
			balance: balance,
			status: 1,
			change: -1,
			user_id: order.user_id,
			note: `订单失效,编号【${order.order_sn}】`

		});
		await think.model("system/message").db(this.db()).add({
			type: 6,
			create_time: new Date().valueOf(),
			user_id: order.user_id,
			content: `订单【${order.order_sn}】失效,退回分红金额:${order.buyer_commission}元,您剩余${balance}元`

		});
		if(!think.isEmpty(order.agency_id)) {

			let agency = await think.model("system/agency").db(this.db()).findOne(order.agency_id);

			await think.model("system/asset").db(this.db()).where({
				user_id: agency.user_id
			}).decrement('amount', order.recommend_commission);
			await think.model("system/asset").db(this.db()).where({
				user_id: agency.user_id
			}).decrement('rebate', order.recommend_commission);

			const balance = await think.model("system/asset").db(this.db()).where({
				user_id: agency.user_id
			}).getField('amount', true);

			await think.model("system/money").db(this.db()).add({
				type: 6,
				create_time: new Date().valueOf(),
				amount: order.recommend_commission,
				balance: balance,
				status: 1,
				change: -1,
				user_id: agency.user_id,
				note: `团队成员订单失效,编号【${order.order_sn}】`

			});
			await think.model("message").db(this.db()).add({
				type: 6,
				create_time: new Date().valueOf(),
				user_id: agency.user_id,
				content: `团队成员订单失效,取消分红金额:${order.recommend_commission}元,您剩余${balance}元`

			});

		}

	}

	/*****
	 * 已绑未结算订单退款
	 *****/

	async orderCancel(order) {
		await think.model("system/asset").db(this.db()).where({
			user_id: order.user_id
		}).decrement('rebate', order.buyer_commission);

		await think.model("system/message").db(this.db()).add({
			type: 6,
			create_time: new Date().valueOf(),
			user_id: order.user_id,
			content: `订单【${order.order_sn}】失效,预估分红减少:${order.buyer_commission}元`

		});
		if(!think.isEmpty(order.agency_id)) {

			let agency = await think.model("system/agency").db(this.db()).findOne(order.agency_id);

			await think.model("system/asset").db(this.db()).where({
				user_id: agency.user_id
			}).decrement('rebate', order.recommend_commission);

			await think.model("system/message").db(this.db()).add({
				type: 6,
				create_time: new Date().valueOf(),
				user_id: agency.user_id,
				content: `团队成员订单失效,预估分红减少:${order.recommend_commission}元`

			});

		}

	}

	/*****
	 * 绑定订单
	 *****/
	async bindOrder(order, asset) {

		let agency = {};
		let row = 0;

		if(!think.isEmpty(order.user_id)) {
			return row;
		}
		if(order.order_status == '13') {
			return row;
		}
		

		if(!think.isEmpty(asset.agency_id)) {

			agency = await think.model("system/agency").findOne(asset.agency_id);

		}
		let level = await think.model("system/user").where({id:asset.user_id}).getField("level",true);
		let orderBuyerRate = await think.model("sys_user_level").where({id: level || 1}).getField("rebate_ratio",true);
		let data = {
			user_id: asset.user_id,
			buyer_rate: orderBuyerRate,
			buyer_commission: (orderBuyerRate * order.effect_prediction).toFixed(2),
		};
		if(!think.isEmpty(agency)) {
			let agencyRate = await think.model("sys_agency_level").where({id: agency.level}).getField("rebate_ratio",true);
			data.agency_id = agency.id;
			data.recommend_rate = agencyRate;
			data.recommend_commission = (data.recommend_rate * order.effect_prediction).toFixed(2);
		};

		row = await this.transaction(async() => {
			await think.model("system/asset").db(this.db()).where({
				user_id: asset.user_id
			}).increment('rebate', data.buyer_commission);
			await think.model("system/message").db(this.db()).add({
				type: 8,
				create_time: new Date().valueOf(),
				user_id: asset.user_id,
				content: `订单【${order.order_sn}】绑定成功,付款:${order.order_amount}元,确认收货后奖励${data.buyer_commission}元`

			});

			if(!think.isEmpty(agency)) {
				await think.model("system/asset").db(this.db()).where({
					user_id: agency.user_id
				}).increment('rebate', data.recommend_commission);
				await think.model("system/message").db(this.db()).add({
					type: 8,
					create_time: new Date().valueOf(),
					user_id: agency.user_id,
					content: `团队成员绑单成功,对方确认收货后您可获得${data.recommend_commission}元`

				});
			};

			const row = await this.setOne(order.id, data);

			if(order.order_status == '3') {
				const newOrder = think.extend(order, data);
				await this.orderBalance(newOrder);

			}

			return row;

		});
		if(row > 0) {
			//收集用户订单编号后6位特征码，用于自动绑单
			await think.model("taoke/feature").thenAdd({
				user_id: asset.user_id,
				code: order.order_sn.slice(-6),
				create_time: new Date().valueOf()
			}, {
				code: order.order_sn.slice(-6),
				user_id: asset.user_id,
			});
		}
		return row;

	}
	/*****
	 * 清除绑单
	 *****/
	async clearBind(order) {
		let agency = {};
		let row = 0;

		if(think.isEmpty(order.user_id)) {
			return row;
		}

		if(!think.isEmpty(order.agency_id)) {

			agency = await think.model("system/agency").findOne(order.agency_id);

		}

		let data = {
			user_id: null,
			buyer_rate: null,
			buyer_commission: null,
			agency_id: null,
			recommend_rate: null,
			recommend_commission: null

		};

		row = await this.transaction(async() => {

			await think.model("system/message").db(this.db()).add({
				type: 8,
				create_time: new Date().valueOf(),
				user_id: order.user_id,
				content: `订单【${order.order_sn}】失效`

			});

			if(!think.isEmpty(agency)) {

				await think.model("system/message").db(this.db()).add({
					type: 8,
					create_time: new Date().valueOf(),
					user_id: agency.user_id,
					content: `团队成员订单失效`

				});
			};
			const row = await this.setOne(order.id, data);
			if(order.order_status == '3') {

				await this.orderRefund(order);

			}

			return row;

		});
		return row;

	}

	async bindOrders(orderNo, userId) {
		try {

			let orders = await this.where({
				order_sn: orderNo
			}).select();
			if(think.isEmpty(orders)) {
				let queue = await think.model("taoke/queue").where({
					order_sn: orderNo
				}).find();
				if(think.isEmpty(queue)) {
					await think.model("taoke/queue").add({
						user_id: userId,
						order_sn: orderNo,
						create_time: new Date().valueOf()
					});
				}
				return {
					errno: 1000,
					errmsg: `订单【${orderNo}】已加入绑定列队`
				};

			}

			let asset = await think.model("system/asset").where({
				user_id: userId
			}).find();
			if(think.isEmpty(asset)) {
				return {
					errno: 1000,
					errmsg: `用户资产不存在`
				};
			}
			let bindNum = 0;
			for(let i = 0; i < orders.length; i++) {
				if(orders[i].user_id) {
					bindNum++;
				}
			}
			if(bindNum == orders.length) {
				return {
					errno: 1000,
					errmsg: `订单已被绑定`
				};
			}
			let num = 0;
			for(let i = 0; i < orders.length; i++) {
				let row = await this.bindOrder(orders[i], asset);
				num = num + row;

			}

			if(num == 0) {
				return {
					errno: 1000,
					errmsg: `绑单失败`
				};
			}
			return {
				errno: 0,
				errmsg: `订单绑定成功`
			};
		} catch(e) {
			console.log(e)
		}

	}
	
	async getMonthIncome(userid){
		
		
			let this_month_begin = think.datetime(think.thisMonthBegin());
			let last_month_begin = think.datetime(think.lastMonthBegin());
			let income = await this.transaction(async() =>{
				
			let agencyId = await think.model("system/agency").db(this.db()).where({user_id: userid}).getField("id",true);
			
			
			let this_income = await this.where({
				user_id: userid,
				create_time: ['>',this_month_begin],
				order_status:['IN',"12,3"]
				
			}).sum("buyer_commission");
			
			let this_share_income = await this.where({
				agency_id: agencyId,
				create_time: ['>',this_month_begin],
				order_status:['IN',"12,3"]
				
			}).sum("recommend_commission");
			
			
			let last_income = await this.where({
				user_id: userid,
				create_time: {'>': last_month_begin, '<': this_month_begin},
				order_status:['IN',"12,3"]
				
			}).sum("buyer_commission");
			
			let last_share_income = await this.where({
				agency_id: agencyId,
				create_time: {'>': last_month_begin, '<': this_month_begin},
				order_status:['IN',"12,3"]
				
			}).sum("recommend_commission");
			
			
			let this_balance_income = await this.where({
				user_id: userid,
				balance_time: ['>',this_month_begin],
				order_status: '3'
				
			}).sum("buyer_commission");
			
			let this_share_balance_income = await this.where({
				agency_id: agencyId,
				balance_time: ['>',this_month_begin],
				order_status: '3'
				
			}).sum("recommend_commission");
			
			let last_balance_income = await this.where({
				user_id: userid,
				balance_time: {'>': last_month_begin, '<': this_month_begin},
				order_status:'3'
				
			}).sum("buyer_commission");
			
			let last_share_balance_income = await this.where({
				agency_id: agencyId,
				balance_time: {'>': last_month_begin, '<': this_month_begin},
				order_status:'3'
				
			}).sum("recommend_commission");
		
			let data = {
				this_income: (this_income + this_share_income).toFixed(2),
				last_income:(last_income + last_share_income).toFixed(2),
				this_balance_income:(this_balance_income + this_share_balance_income).toFixed(2),
				last_balance_income:(last_balance_income + last_share_balance_income).toFixed(2)
			}
			
			return  data;
				
			});
			return income;
			
	}
	

};